import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/getPageTitle'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
const systemList = ['pado']

router.beforeEach(async(to, from, next) => {
  console.log('to', to)
  // 判断由关联系统跳转过来的页面无需登陆
  if (to.path === '/home' && to.query.sources && systemList.indexOf(to.query.sources.toLowerCase()) !== -1) {
    setToken('Admin-Token', 'coherentSystem')
  }
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken('Admin-Token')
  if (hasToken) {
    if (to.path === '/login') {
      // 登陆成功跳转首页
      next({ path: '/' })
      NProgress.done()
    } else {
      // 是否已获取用户权限
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      // 已获取用户权限，直接跳转
      if (hasRoles) {
        next()
      } else {
        // 重新获取用户权限
        try {
          // 获取用户权限，superAdmin为系统管理员
          const { roles } = await store.dispatch('user/getInfo')

          // 通过权限渲染权限内的菜单
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          // dynamically add accessible routes
          router.addRoutes(accessRoutes)
          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          console.log('error', error)
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    // 跳转到登录页
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login?redirect=${to.path}`)
      // NProgress.done()
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
